Skip to content

JSpecify: support annotated type arguments from an enclosing class - #1699

Merged
msridhar merged 3 commits into
apache:masterfrom
dbwiddis:jspecify-enclosing-class-836
Aug 13, 2026
Merged

msridhar merged 3 commits into
apache:masterfrom
dbwiddis:jspecify-enclosing-class-836

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Un-ignores overrideAnonymousNestedClass, which exercises an anonymous class instantiated via a qualified new expression with two levels of generics:

class Test {
  class Wrapper<P extends @Nullable Object> {
    abstract class Fn<R extends @Nullable Object> {
      abstract R apply(P p);
    }
  }
  void anonymousNestedClasses() {
    Wrapper<@Nullable String>.Fn<String> fn1 = (this.new Wrapper<@Nullable String>()).new Fn<String>() {
      public String apply(String s) { return s; }
    };
  }
}

Fn.apply(P p) references the outer class Wrapper's type variable P. The @Nullable annotation for P lives in the qualifier sub-expression (this.new Wrapper<@Nullable String>()), not in the Fn<String> part naming the class actually being instantiated.

Diagnosis

Running the ignored test (rather than assuming the issue title described the actual behavior) showed this is a hard, uncaught crash, not a silently-missed diagnostic:

com.google.common.base.VerifyException: <anonymous com.uber.Test.Wrapper<java.lang.String>.Fn<java.lang.String>> is not assignable to com.uber.Test.Wrapper<P>.Fn<java.lang.String>
	at com.google.common.base.Verify.verify(Verify.java:411)
	at com.uber.nullaway.generics.GenericsChecks.getTypeForSymbol(GenericsChecks.java:2472)
	at com.uber.nullaway.generics.GenericsChecks.getGenericMethodReturnTypeNullness(GenericsChecks.java:2447)
	at com.uber.nullaway.NullAway.overriddenMethodReturnsNonNull(NullAway.java:1339)

GenericsChecks.getTreeType's NewClassTree handling only ever consulted newClassTree.getIdentifier() (Fn<String>) via PreservedAnnotationTreeVisitor, never newClassTree.getEnclosingExpression() (the qualifier this.new Wrapper<@Nullable String>()). PreservedAnnotationTreeVisitor.visitParameterizedType built the enclosing type from baseType.getEnclosingType() — Fn's statically-declared enclosing type, Wrapper<P>, with the raw, unsubstituted type variable P still present, completely unconnected to what the qualifier expression actually evaluates to. This is a materially different (and worse) bug than "annotations get dropped" — the enclosing type was never resolved to any real instantiation at all. getTypeForSymbol's own sanity-check verify() correctly caught the resulting type mismatch and threw.

This gap was left open deliberately by #837 ("JSpecify: initial handling of generic enclosing types for inner classes"), whose commit message states it fixed the enclosing-type case for ordinary declared types but explicitly did not yet handle NewClassTrees.

Fix

Adds GenericsChecks.withEnclosingTypeFromQualifier, called from getTreeType's NewClassTree branch. It reads newClassTree.getEnclosingExpression(); if present, it recursively calls the existing getTreeType on that qualifier to get its own correctly-substituted, annotated type (this recursion is bounded by the qualifier-chain depth in the source, so arbitrarily deep nesting is handled for free with no new logic), then splices that in as the enclosing type via TypeMetadataBuilder.createClassType, replacing the broken baseType.getEnclosingType() result. If there's no qualifying expression (the ordinary, unqualified anonymous-class case #808 already handles correctly), the type is returned unchanged.

This is separate from, and does not touch, the diamond-operator anonymous-class gap tracked in #1475 (a distinct, early-bailout branch in the same method).

Fixes #836

Testing

  • Ran overrideAnonymousNestedClass with @Ignore removed before writing any fix, to confirm the actual failure mode (the crash above) rather than assume it from the issue text.
  • With the fix in place, ran overrideAnonymousNestedClass again: passes, no crash, expected diagnostic reported.
  • Added overrideAnonymousDeeplyNestedClass, a 3-level-deep qualified-nesting case (Wrapper.Middle.Fn), to confirm the recursive approach generalizes beyond the 2-level case in the original test.
  • Negative control: temporarily disabled the new logic two different ways (short-circuiting the call site, and forcing getEnclosingExpression() to null inside the helper) and reran both tests — both failed (reproducing the original crash) without the fix, confirming they're load-bearing rather than passing vacuously. Reverted both before finalizing.
  • ./gradlew :nullaway:test (full module suite): 914 tests, 0 failures, 0 errors.
  • ./gradlew :nullaway:spotlessJavaCheck.

AI usage disclosure

I used Claude Code for this PR. I asked it to scope the issue, which involved parallel research into how NullAway resolves types for anonymous classes and what the prior partial fix (#837) had and hadn't addressed; I reviewed those findings before agreeing to proceed. Before writing any fix, Claude ran the ignored test to confirm the actual failure mode rather than relying on the issue title, which surfaced that this is an uncaught crash rather than a silently-missed diagnostic. Claude then implemented the fix and wrote the additional test coverage, including a negative-control check (temporarily disabling the fix to confirm the new tests actually fail without it). I reviewed the resulting diff and asked follow-up questions to confirm my own understanding of the change, including what TYPE_METADATA_BUILDER.createClassType returns and whether the recursive call in withEnclosingTypeFromQualifier risks a stack overflow on deeply nested qualifiers (it doesn't: the recursion is bounded by the qualifier-chain depth in the source, which is small in any realistic code). I have read and understood all the changes in this PR.

Summary by CodeRabbit

  • Bug Fixes

    • Improved nullability analysis for qualified inner-class constructor expressions, preserving inferred type annotations in generic contexts.
    • Correctly handles nullability compatibility for anonymous classes nested within generic and deeply nested types.
  • Tests

    • Enabled coverage for anonymous nested-class overrides.
    • Added test coverage for deeply nested generic anonymous classes and nullable versus non-null parameters.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: cd17d9a0-c0e1-4fa1-aff5-e3429de99259

📥 Commits

Reviewing files that changed from the base of the PR and between d9aedea and 952f84a.

📒 Files selected for processing (1)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java

Walkthrough

GenericsChecks.getTreeType now corrects qualified inner-class constructor types by using the qualifier’s inferred enclosing type while preserving annotations. JSpecify generics tests enable the nested anonymous-class case and add coverage for doubly nested generic classes with nullable and non-null parameter overrides.

Possibly related PRs

  • uber/NullAway#1248: Both changes update GenericsChecks.getTreeType for generic constructor type handling.
  • uber/NullAway#1305: Both changes address generic and anonymous nested-class type resolution.
  • uber/NullAway#1428: Both changes update GenericsChecks.getTreeType for generic type annotation preservation.

Suggested labels: jspecify

Suggested reviewers: msridhar, yuxincs

Mergeability Score: ⚪ Minimal · up to 952f8

The change is localized to qualified nested generic type handling and includes focused regression coverage; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes support for annotated type arguments from an enclosing class.
Linked Issues check ✅ Passed The implementation and tests address issue #836 by supporting annotated enclosing type arguments and enabling the ignored nested-class test.
Out of Scope Changes check ✅ Passed All changes are limited to the implementation and tests required to support annotated type arguments from enclosing classes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…pache#836)

The previously-@ignore'd test overrideAnonymousNestedClass exercises an
anonymous class instantiated via a qualified new expression with two
levels of generics, e.g. (this.new Wrapper<@nullable String>()).new
Fn<String>() {...}, where the abstract method being overridden,
Fn.apply(P p), references the OUTER class Wrapper's type variable P.

Running the test (rather than assuming from the issue text) showed this
was a hard, uncaught VerifyException crash, not a silently-missed
diagnostic: GenericsChecks.getTreeType's NewClassTree handling only
ever consulted newClassTree.getIdentifier() (Fn<String>) via
PreservedAnnotationTreeVisitor, and PreservedAnnotationTreeVisitor's
visitParameterizedType built the enclosing type from
baseType.getEnclosingType() -- Fn's statically-declared enclosing type
Wrapper<P>, with the raw type variable P, completely unconnected to the
qualifier expression's actual instantiation. getTypeForSymbol's
sanity-check verify() correctly caught the resulting type mismatch and
threw.

Adds GenericsChecks.withEnclosingTypeFromQualifier, which recovers the
qualifier expression's own correctly-substituted type (recursing via
the existing getTreeType, so arbitrary nesting depth is handled for
free) and splices it in as the enclosing type, replacing
baseType.getEnclosingType()'s incorrect result. This is separate from,
and does not touch, the diamond-operator anonymous-class gap tracked in
apache#1475.
@dbwiddis
dbwiddis force-pushed the jspecify-enclosing-class-836 branch from d9aedea to 486a447 Compare August 12, 2026 01:42

@msridhar msridhar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One minor comment, otherwise LGTM!

Comment on lines +1969 to +1971
if (type == null) {
return null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think type can be null? Let's get rid of this check and the @Nullable parameter annotation, if I'm right

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. I should probably trust your own annotations!

Dug through this enough to find castToNonNull to confirm your comment.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We also have a :nullaway:buildWithNullAway task that runs NullAway on itself, so those annotations are checked 🙂

@codecov

codecov Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.88%. Comparing base (56bd5ad) to head (a517140).

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 84.61% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1699      +/-   ##
============================================
- Coverage     87.89%   87.88%   -0.01%     
- Complexity     3173     3175       +2     
============================================
  Files           109      109              
  Lines         10755    10767      +12     
  Branches       2173     2175       +2     
============================================
+ Hits           9453     9463      +10     
- Misses          617      618       +1     
- Partials        685      686       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

type is always the result of typeWithPreservedAnnotations(paramTypedTree),
which is never null when called with a ParameterizedTypeTree, so the check
and @nullable annotation were unreachable.
@msridhar
msridhar enabled auto-merge (squash) August 13, 2026 01:44
@msridhar
msridhar merged commit f3febf6 into apache:master Aug 13, 2026
9 of 10 checks passed
@dbwiddis
dbwiddis deleted the jspecify-enclosing-class-836 branch August 13, 2026 02:30
dbwiddis added a commit to dbwiddis/NullAway that referenced this pull request Aug 14, 2026
…ents

Issue apache#1274 reported a missing warning when assigning a qualified inner
class creation to an incompatible enclosing type. Bisecting shows the
false negative was fixed by apache#1699, which corrected the enclosing type of
a NewClassTree to come from the qualifier expression rather than the
statically-declared enclosing type. Adds a regression test so the
behavior stays fixed.

Fixes apache#1274
msridhar pushed a commit that referenced this pull request Aug 14, 2026
…ents (#1703)

## Summary

#1274 reports that NullAway misses a warning when a qualified
inner-class creation is assigned to a
variable whose *enclosing* type argument is incompatible:

```java
class A<X extends @nullable Object> { class B<Y extends @nullable Object> {} }
class C<X extends @nullable Object> extends A<X> { class D<Y extends @nullable Object> extends A<X>.B<Y> {} }

C<@nullable String> c = new C<>();
A<String>.B<@nullable String> unused = c.new D<@nullable String>();  // should warn
```

Rather than assume the issue title described current behavior, I ran the
example verbatim as a test
first. On current `master` NullAway **does** report the expected error:

```
warning: [NullAway] incompatible types: Test.C<@nullable String>.D<@nullable String>
  cannot be converted to Test.A<String>.B<@nullable String>
  (Test.C<@nullable String>.D<@nullable String> is a subtype of Test.A<@nullable String>.B<@nullable String>)
```

Running the same test against `56bd5ad2` — the commit immediately
preceding #1699 — it reports nothing.
So this false negative was fixed as a side effect of #1699.

That makes sense mechanically. Before #1699, `getTreeType` typed `c.new
D<@nullable String>()` from the
`D<@nullable String>` identifier alone, and
`PreservedAnnotationTreeVisitor` took the enclosing type from
`baseType.getEnclosingType()` — `D`'s statically-declared enclosing type
`C<X>`, with `X` unsubstituted.
Comparing `C<X>.D<@nullable String>` against `A<String>.B<@nullable
String>` surfaces no nullability
conflict, since `X` carries no annotation either way. #1699's
`withEnclosingTypeFromQualifier` types the
qualifier `c` instead, yielding `C<@nullable String>.D<@nullable
String>`; `D`'s supertype then
substitutes to `A<@nullable String>.B<@nullable String>` and the
mismatch against the declared
`A<String>.B<...>` becomes visible.

This PR adds a regression test so the behavior stays fixed. No
production code changes.

## Testing

- Added `innerClassInheritingEnclosingTypeArgs` in `GenericsTests.java`,
covering the reported error case
plus two negative controls: a correctly-typed `@Nullable` enclosing
instance, and a non-`@Nullable` one.
Both must stay silent, so the test also pins down that we don't
over-report here.
- Negative control on the assertion itself: temporarily changed the
erroring line's declared type to the
correct one and confirmed the test fails with `Did not see an error on
line 14 ... There were no errors`,
verifying the expectation is load-bearing and not incidentally
satisfied.
- Confirmed the test fails (reports nothing) at `56bd5ad2` and passes on
`master`.
- `./gradlew :nullaway:test` — 919 tests, 0 failures.

Fixes #1274

## AI usage disclosure

> I used Claude Code for this PR. It ran the issue's repro, bisected to
determine the false negative had
> already been fixed by my earlier PR #1699, explained the mechanism,
and drafted the regression test.
> I asked follow-up questions about the enclosing-type handling in
`getTreeType` and
> `PreservedAnnotationTreeVisitor`, and verified the test is
load-bearing by mutating it locally.
> I have read and understood all the changes in this PR.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Tests**
* Added regression coverage for generic type arguments inherited by
inner classes.
* Verified compatible nullable assignments and detection of incompatible
nullable-to-non-null assignments.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSpecify: support annotated type arguments from an enclosing class

2 participants